<?php

use Drupal\commerce_weight_shipping\Entity\CommerceWeightShipping;
use Drupal\commerce_weight_shipping\Entity\CommerceWeightShippingItem;

function commerce_weight_shipping_commerce_weight_shipping_entity_form($form, &$form_state, CommerceWeightShipping $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'commerce_weight_shipping') . '/commerce_weight_shipping.forms.inc';
  $form_state[CommerceWeightShipping::class] = $e;

  $form['title'] = [
    '#title' => t('标题'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->title,
  ];
  $form['first'] = [
    '#title' => t('首重KG'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->first,
    '#element_validate' => ['element_validate_number'],
  ];
  $form['first_cost'] = [
    '#title' => t('首重费用'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->first_cost / 100,
    '#element_validate' => ['element_validate_number'],
  ];
  $form['renewal'] = [
    '#title' => t('续重KG'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->renewal,
    '#element_validate' => ['element_validate_number'],
  ];
  $form['renewal_cost'] = [
    '#title' => t('续重费用'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->renewal_cost / 100,
    '#element_validate' => ['element_validate_number'],
  ];
  $form['status'] = [
    '#type' => 'checkbox',
    '#title' => t('启用'),
    '#default_value' => $e->status,
  ];
  //@todo 需要做店铺归属
  $form['store_id'] = [
    '#title' => t('所属店铺'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->store_id,
    '#element_validate' => ['element_validate_number'],
  ];

  $form["items"] = [
    '#type' => 'fieldset',
    '#title' => t('特殊区域覆盖'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#tree' => TRUE,
    '#description' => t('下方可以设置特殊区域运费单独计算,可按省市区任意精度.从上至下查找'),
  ];
  $form["items"]['ii'] = [
    '#type' => 'item',
    '#prefix' => '<div id="items-form-wrapper">',
    '#suffix' => '</div>',
    '#theme' => 'commerce_weight_shipping_form_items',
  ];
  if (empty($form_state['items'])) {
    $items = entity_load('commerce_weight_shipping_item', FALSE, [
      'cwsid' => $e->id,
    ]);
    if (!empty($items)) {
      usort($items, 'commerce_weight_shipping_sort_weight');
      $form_state['items'] = $items;
    }
    else {
      $form_state['items'] = [];
    }
  }

  $json = variable_get_value('commerce_weight_shipping:national:options');
  $nationalOptions = drupal_json_decode($json);

  foreach ($form_state['items'] as $i => $item) {
    if ($item instanceof CommerceWeightShippingItem) {
      $form['items']['ii'][$i] = [
        'id' => [
          '#type' => 'value',
          '#value' => $item->id,
        ],
        'note' => [
          '#title' => t('备注'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#size' => 16,
          '#default_value' => $item->note,
        ],
        'national' => [
          '#title' => t('统计局行政区编码'),
          '#title_display' => 'invisible',
          '#required' => TRUE,
          '#size' => 16,
          '#default_value' => $item->national,
          '#description' => t('需要单独覆盖的地区.'),
          '#type' => 'select',
          '#options' => $nationalOptions,
          '#chosen' => TRUE,
        ],
        'first' => [
          '#title' => t('首重KG'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#required' => TRUE,
          '#size' => 16,
          '#default_value' => $item->first,
        ],
        'first_cost' => [
          '#title' => t('首重费用'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#required' => TRUE,
          '#size' => 4,
          '#default_value' => $item->first_cost / 100,
          '#element_validate' => ['element_validate_number'],
        ],
        'renewal' => [
          '#title' => t('续重KG'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#required' => TRUE,
          '#size' => 4,
          '#default_value' => $item->renewal,
          '#element_validate' => ['element_validate_number'],
        ],
        'renewal_cost' => [
          '#title' => t('续重费用'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#required' => TRUE,
          '#size' => 16,
          '#default_value' => $item->renewal_cost / 100,
          '#element_validate' => ['element_validate_number'],
        ],
        //        'status' => [
        //          '#title' => t('启用'),
        //          '#title_display' => 'invisible',
        //          '#type' => 'checkbox',
        //          '#default_value' => $item->status,
        //        ],
        'weight' => [
          '#type' => 'weight',
          '#title' => t('Weight'),
          '#default_value' => $item->weight,
          '#delta' => 10,
          '#title_display' => 'invisible',
        ],
      ];
    }
  }
  $form["items"]['add_item'] = [
    '#type' => 'submit',
    '#value' => t('添加特殊区域覆盖'),
    '#submit' => ['commerce_weight_shipping_form_items_add_item_submit'],
    '#ajax' => [
      'callback' => 'commerce_weight_shipping_form_items_add_item_callback',
      'wrapper' => 'items-form-wrapper',
    ],
  ];

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function commerce_weight_shipping_form_items_add_item_submit($form, &$form_state) {
  $form_state['items'][] = new CommerceWeightShippingItem();
  $form_state['rebuild'] = TRUE;
}

function commerce_weight_shipping_form_items_add_item_callback($form, &$form_state) {
  return $form['items']['ii'];
}

function theme_commerce_weight_shipping_form_items($variables) {
  $output = '';
  $form = $variables['form'];
  $rows = [];
  foreach (element_children($form) as $id) {
    $form[$id]['weight']['#attributes']['class'] = ['item-weight'];
    $rows[] = [
      'data' => [
        drupal_render($form[$id]['note']),
        drupal_render($form[$id]['national']),
        drupal_render($form[$id]['first']),
        drupal_render($form[$id]['first_cost']),
        drupal_render($form[$id]['renewal']),
        drupal_render($form[$id]['renewal_cost']),
        //        drupal_render($form[$id]['status']),
        drupal_render($form[$id]['weight']),
      ],
      'class' => ['draggable'],
    ];
  }
  $header = [
    t('备注'),
    t('统计局行政区编码'),
    t('首重KG'),
    t('首重费用'),
    t('续重KG'),
    t('续重费用'),
    //    t('启用'),
    t('Weight'),
  ];

  $table_id = 'items-table';
  $form['items_markup']['markup']['#markup'] = theme('table', [
    'header' => $header,
    'rows' => $rows,
    'attributes' => ['id' => $table_id],
  ]);
  $output .= drupal_render_children($form);
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'item-weight');
  return $output;
}

function commerce_weight_shipping_commerce_weight_shipping_entity_form_submit($form, &$form_state) {
  $e = $form_state[CommerceWeightShipping::class];
  if ($e instanceof CommerceWeightShipping) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->first_cost = ceil($e->first_cost * 100);
    $e->renewal_cost = ceil($e->renewal_cost * 100);
    $e->save();
    $values = $form_state['values'];
    if (!empty($values['items']['ii'])) {
      $items = $values['items']['ii'];
      foreach ($items as $item) {
        $id = $item['id'];
        if (!empty($id)) {
          $eItem = commerce_weight_shipping_item_load($id);
        }
        else {
          $eItem = new CommerceWeightShippingItem();
        }
        $eItem->cwsid = $e->id;
        $eItem->weight = $item['weight'];
        $eItem->note = $item['note'];
        $eItem->national = $item['national'];
        $eItem->first = $item['first'];
        $eItem->first_cost = ceil($item['first_cost'] * 100);
        $eItem->renewal = $item['renewal'];
        $eItem->renewal_cost = ceil($item['renewal_cost'] * 100);
        //      $eItem->status = $item['status'];
        $eItem->save();
      }
    }
  }
}

function commerce_weight_shipping_commerce_weight_shipping_delete_form($form, &$form_state, CommerceWeightShipping $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'commerce_weight_shipping') . '/commerce_weight_shipping.forms.inc';
  $form_state[CommerceWeightShipping::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/commerce_weight_shipping/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function commerce_weight_shipping_commerce_weight_shipping_delete_form_submit($form, &$form_state) {
  $e = $form_state[CommerceWeightShipping::class];
  if ($e instanceof CommerceWeightShipping) {
    $e->delete();
  }
}
